<template>
  <div class="m-container">
    <h2>
      任务：{{taskInfo?.name}}【{{taskInfo?.taskType}}】
    </h2>
    <el-divider content-position="left">说明：{{taskInfo?.note}}</el-divider>
    <div>
      <el-form :inline="true" label-width="80">
        <el-form-item label="部门">
          <el-select v-model="deptWageTaskId" placeholder="请选择部门" @change="selectTask">
            <el-option v-for="item in taskInfo.deptWageTaskItems" :key="item.id" :label="item.deptName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="绩效总额：">
          <h3>¥{{deptTotalMerit}}</h3>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="staff" style="width: 100%" height="80%">
      <el-table-column prop="name" label="姓名" width="180"></el-table-column>
      <el-table-column label="性别" width="180">
        <template #default="scope">
          {{scope.row.sex === 'M' ? '男' : '女'}}
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="180"></el-table-column>
      <el-table-column>
        <template #header>
          <h3>已分配：¥{{meritSum}}</h3>
        </template>
        <template #default="scope">
          <div v-if="editState">
            <h3 v-if="!rowEditing(scope.row)" @click="changeRowState(scope.row)">{{scope.row.meritPay}}</h3>
            <el-input v-model="scope.row.meritPay" v-if="rowEditing(scope.row)" type="number" @blur="changeRowState(scope.row)"></el-input>
          </div>
          <div v-else>
            <h3>{{scope.row.meritPay}}</h3>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="editState">
        <template #header>
          <el-button type="info" plain size="mini" @click="saveMerits">提交</el-button>
        </template>
        <template #default="scope">
          <el-button @click="changeRowState(scope.row)" type="text" size="small">{{rowEditing(scope.row)?'确认':'编辑'}}</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts">
import {defineComponent} from 'vue'
import {getTaskById,getDeptSalaries,saveDeptSalaries} from '@/api/salary'
import _ from 'lodash'
import { ElMessage,ElMessageBox } from 'element-plus'
export default defineComponent({
  data() {
    return {
      taskInfo: {
        id: '',
        name: '',
        note: '',
        state: '',
        taskType: '',
        deptWageTaskItems: []
      },
      deptWageTaskId: '',
      currentTask: undefined,
      staff: []
    }
  },
  created() {
    this.getTaskInfo()
  },
  computed: {
    // 部门绩效总额
    deptTotalMerit() {
      if(this.currentTask) {
        let ct = this.currentTask as any
        return _.round(Number(ct.meritPay) + Number(ct.totalMerit))
      }
      return 0
    },
    // 计算总和
    meritSum() {
      let sum = 0;
      for(let s of this.staff) {
        sum += Number((s as any).meritPay)
      }
      return _.round(sum, 2)
    },
    // 计算行是否可编辑
    editState() {
      let tk = this.taskInfo as any
      let ct = this.currentTask as any
      return tk?.state == 1 && ct?.state == 1
    }
  },
  methods: {
    // 获取任务信息
    getTaskInfo() {
      getTaskById(_.toNumber(this.$route.params.id)).then(res => {
        this.taskInfo = res.data
      })
    },
    // 根据编号获取任务对象
    getDeptTaskInfo(taskId: string) {
      for(let task of this.taskInfo.deptWageTaskItems) {
        if(task['id'] === taskId) {
          return task
        }
      }
    },
    // 选择任务
    selectTask(taskId: string) {
      this.currentTask = this.getDeptTaskInfo(taskId)
      this.getSalaryList(taskId)
    },
    // 获取部门职工绩效列表
    getSalaryList(taskId: string) {
      // 如果未选择部门
      if(_.isEmpty(taskId)) {
        ElMessage.error('请选择部门')
        return
      }
      getDeptSalaries(taskId).then(res => {
        this.staff = res.data
        // console.log(this.staff)
      })
    },
    // 获取编辑状态
    rowEditing(row: any) {
      return row?.edit || false
    },
    changeRowState(row: any) {
      row.meritPay = _.toNumber(row.meritPay)
      row.edit=!row.edit
    },
    // 保存设置
    saveMerits() {
      // 如果没有选择任务，则直接返回
      if(!this.currentTask){
        return
      }
      let ct = this.currentTask as any
      for(let row of this.staff) {
        let r = row as any
        if(r.edit === true){
          ElMessage.error(`请先确认"${r.name}"的绩效金额后再提交`)
          return
        }
      }
      
      let totalMerit = this.deptTotalMerit
      let cfmsg = '提交后将无法修改，确定提交么?'
      // 绩效超额
      if(this.meritSum > totalMerit) {
        ElMessage.error('员工绩效总和大于部门绩效总额，请检查后再提交')
        return
      }
      else if(this.meritSum < totalMerit) {
        cfmsg = `尚有未分配的绩效:¥${totalMerit - this.meritSum},` + cfmsg
      }
      ElMessageBox.confirm(cfmsg,"提示",{ confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
      .then(()=>{
        // 保存绩效工资列表
        saveDeptSalaries(ct.id, this.staff).then(res => {
          if(res.data === true) {
            (this.currentTask as any).state = 2
            ElMessage.success('保存成功')
          }
        })
      }).catch(() => {})
    }
  }
})
</script>

<style>

</style>